﻿package net.eascn.flowerThief.dao
{
	import com.adobe.xml.syndication.atom.Atom10;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.CursorManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.InvokeEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import net.eascn.flowerThief.model.ModelLocator;
	import net.eascn.flowerThief.utils.PhotoUtil;	

	/**
	 * @author eas
	 * @created  2009-3-2 - 上午11:45:06
	 */
	public class Provider
	{
		private static var _instatnce : Provider;

		/**
		 * @return 返回一个 Provider的单件实例
		 */
		public static function getInstance() : Provider
		{
			if (_instatnce == null)
				_instatnce = new Provider(new SingletonForce());
			return _instatnce;
		}

		public function Provider(singletonForce : SingletonForce) 
		{
			_service = new HTTPService();
			_service.addEventListener(FaultEvent.FAULT, serviceHandler);
			_service.addEventListener(ResultEvent.RESULT, serviceHandler);
			_service.addEventListener(InvokeEvent.INVOKE, serviceHandler);
		}
		
		

		private var _service : HTTPService;

		private var _model : ModelLocator;

		private function get model() : ModelLocator
		{
			if (_model == null) 
			{
				_model = ModelLocator.getInstance();
			}
			return _model;
		}
		
		private var _isExecuting:Boolean = false;
		private var _mark:String = '';
		public function query(url : String,mark:String) : Boolean
		{
			if(_isExecuting)
				return false;
			_service.url = url;
			_service.resultFormat = HTTPService.RESULT_FORMAT_E4X;
			_service.send();
			CursorManager.setBusyCursor();
			_isExecuting = true;
			_mark = mark;
			return true;
		}

		private function serviceHandler(event : Event) : void
		{
			
			CursorManager.removeBusyCursor();
			_isExecuting = false;
			switch (event.type)
			{
				case ResultEvent.RESULT:
					parseRSS(ResultEvent(event).result.toString());
				break;
				case FaultEvent.FAULT:
					Alert.show('失败','失败');
				break;
				case InvokeEvent.INVOKE:
				break;
			}
		}
		
		private function parseRSS(data:String):void
{

	//XMLSyndicationLibrary does not validate that the data contains valid
	//XML, so you need to validate that the data is valid XML.
	//We use the XMLUtil.isValidXML API from the corelib library.
//			if(!XMLUtil.isValidXML(data))
//			{
//				trace("Feed does not contain valid XML.");
//				return;
//			}	

	//create RSS20 instance
		var rss:Atom10= new Atom10();

		//parse the raw rss data
		rss.parse(data);

		//get all of the items within the feed
		var items:Array = rss.entries;

		PhotoUtil.parseEntrys(items);
		//loop through each item in the feed
		var model:ModelLocator = ModelLocator.getInstance();
		(model[_mark] as ArrayCollection).source = items;
		
}

		
	}
}

class SingletonForce
{
}